//
//  PhotoPickController.swift
//  selectPhoto
//
//  Created by 孟祥群 on 2018/4/24.
//  Copyright © 2018年 孟祥群. All rights reserved.
//

import UIKit
import Photos
enum PageType{
    case List
    case RecentAlbum
    case AllAlbum
}
protocol PhotoPickerControllerDelegate: class{
    func onImageSelectFinished(images: [PHAsset])
}
class PhotoPickController: UINavigationController {
    // the select image max number
    static var imageMaxSelectedNum = 0
    
    // already select total
    static var alreadySelectedImageNum = 0
    
    weak var imageSelectDelegate: PhotoPickerControllerDelegate?
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    
    /// 重新init方法 定义跳转的样式
    ///
    /// - Parameter type: 图片列表 图片详细
    init(type:PageType){
        let rootViewController = PhotoAlbumsTableViewController(style:.plain)
        super.init(rootViewController: rootViewController)
        
        if type == .RecentAlbum || type == .AllAlbum {
            let currentType = type == .RecentAlbum ? PHAssetCollectionSubtype.smartAlbumRecentlyAdded : PHAssetCollectionSubtype.smartAlbumUserLibrary
            let results = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype:currentType, options: nil)
            if results.count > 0 {
                if let model = self.getModel(collection: results[0]) {
                    if model.count > 0 {
                        let layout = PhotoCollectionViewController.configCustomCollectionLayout()
                        let controller = PhotoCollectionViewController(collectionViewLayout: layout)
                        
                        controller.fetchResult = model as? PHFetchResult<PHObject>;
                        self.pushViewController(controller, animated: false)
                    }
                }
            }
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func getModel(collection: PHAssetCollection) -> PHFetchResult<PHAsset>?{
        let fetchResult = PHAsset.fetchAssets(in: collection, options: PhotoFetchOptions.shareInstance)
        if fetchResult.count > 0 {
            return fetchResult
        }
        return nil
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
       
    }
    
    func imageSelectFinish(){
        if self.imageSelectDelegate != nil {
            self.dismiss(animated: true, completion: nil)
            self.imageSelectDelegate?.onImageSelectFinished(images: PhotoImage.instance.selectedImage)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
